import React, { Component } from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    Image,
    Modal,
    View,
    TextInput,
    Alert,
    ScrollView,
    RefreshControl,
    SectionList, 
    TouchableWithoutFeedback,
    TouchableOpacity,
    ViewPagerAndroid,
    ProgressBarAndroid,
} from 'react-native';
import TabLoadding from '../ui/tabLadding'
// import FriendListItem from '../ui/friendListItem'
import px2dp from '../config/pxToDp';
import CitySectionList from '../ui/CitySectionList'
import FriendListHeader from '../ui/friendListHeader';
import getData from '../config/fetch'
const ITEM_HEIGHT = 50; //item的高度
const HEADER_HEIGHT = 24;  //分组头部的高度
const SEPARATOR_HEIGHT = 0;  //分割线的高度

export default class FriendScene extends Component {

    //no
    async getCityInfos() {
        let data = await require('./city.json');
        let jsonData = data.data
        //每组的开头在列表中的位置
        let totalSize = 0;
        //SectionList的数据源
        let cityInfos = [];
        //分组头的数据源
        let citySection = [];
        //分组头在列表中的位置
        let citySectionSize = [];
        for (let i = 0; i < jsonData.length; i++) {
            citySectionSize[i] = totalSize;
            //给右侧的滚动条进行使用的
            // citySection[i] = jsonData[i].title;
            let section = {}
            section.key = jsonData[i].title;
            section.data = jsonData[i].city;
            for (let j = 0; j < section.data.length; j++) {
                section.data[j].key = j
            }
            cityInfos[i] = section;
            //每一项的header的index
            totalSize += section.data.length + 1
        }
        // this.setState({ data: cityInfos, sections: citySection, sectionSize: citySectionSize })
        this.setState({ data: cityInfos,  sectionSize: citySectionSize })
    }


    constructor(props) {
        super(props);
        this.state = {
            data: [],
            sections: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','#'],
            // sections: [],
            sectionSize: [],
            loaddingState: 0
        }
       getData.getData('?m=User&c=Api&a=friendList&uid=200058','',this.props).then((res)=>{
           let Data = res.data
            if (Data){
                var info = [];
                for (let i in Data) {
                    let key = Data[i].sort;
                    if (parseInt(key) != 'NaN') {
                        var order = key == '#' ? 27 : (key.charCodeAt() - 96)
                    } else {
                        var order = parseInt(key);
                    }
                    if (info.length == 0) {
                        info[i] = [];
                        info[i]['title'] = key
                        info[i]['index'] = order
                        info[i]['data'] = []
                        info[i]['data'].push(Data[i]);
                    } else {
                        for (let index = 0; index < info.length; index++) {
                            if (info[index]["title"] == key) {
                                info[index]['data'].push(Data[i]);
                                break;
                            } else {
                                if (index == (info.length - 1)) {
                                    let len = info.length
                                    info[len] = [];
                                    info[len]['title'] = key
                                    info[len]['index'] = order
                                    info[len]['data'] = []
                                }
                            }
                        }
                    }
                }
                for (let i in info) {
                    for (let index in info) {
                        if (info[i]['index'] < info[index]['index']) {
                            [info[i], info[index]] = [info[index], info[i]]
                        }
                    }
                }
                //转数字
                console.log(info)
                // this.getCityInfos()

                let jsonData = info
                //每组的开头在列表中的位置
                let totalSize = 0;
                //SectionList的数据源
                let cityInfos = [];
                //分组头的数据源
                let citySection = [];
                //分组头在列表中的位置
                let citySectionSize = [];
                for (let i = 0; i < jsonData.length; i++) {
                    // console.log(jsonData[i])
                    // console.log(i)
                    citySectionSize[i] = totalSize;
                    //给右侧的滚动条进行使用的
                    citySection[i] = jsonData[i].title;
                    let section = {}
                    section.key = jsonData[i].title;
                    section.data = jsonData[i].data;
                    for (let j = 0; j < section.data.length; j++) {
                        section.data[j].key = j
                    }
                    cityInfos[i] = section;
                    //每一项的header的index
                    totalSize += section.data.length + 1
                }
                this.setState({
                    data: cityInfos,
                    sections: citySection,
                    sectionSize: citySectionSize
                })
                // this.setState({
                //     data: cityInfos,
                //     sectionSize: citySectionSize
                // })

                this.setState({
                    loaddingState: 1
                })
            }else{
                this.setState({
                    loaddingState: 0
                })
            }
            
       }).catch(err=>{
           console.log(err)
       })
    }

    render() {
        if (this.state.loaddingState == 0) {

            return <TabLoadding />
        }else{
            if (this.state.data.length > 0) {
                return (
                    <View style={{ paddingTop: Platform.OS === 'android' ? 0 : 20, backgroundColor: '#fff'}}>
                        
                        <View>
                            <SectionList
                                ref='list'
                                enableEmptySections
                                renderItem={this._renderItem}
                                ListHeaderComponent={<FriendListHeader search={()=>{
                                        this.props.navigation.navigate('searchScene', {
                                            searchType: 'searchUserFriend',
                                        })
                                    }}
                                    myGroupChat={()=>{
                                        this.props.navigation.navigate('myGroupChatScene' )
                                    }}
                                />}
                                renderSectionHeader={this._renderSectionHeader}
                                sections={this.state.data}
                                getItemLayout={this._getItemLayout} />

                            <CitySectionList
                                sections={this.state.sections}
                                onSectionSelect={this._onSectionselect} />
                        </View>
                    </View>
                )
            } else {
                return (
                    <View style={{ paddingTop: Platform.OS === 'android' ? 0 : 20, backgroundColor: '#fff'}}>
                        <FriendListHeader search={()=>{
                                this.props.navigation.navigate('searchScene', {
                                    searchType: 'searchUserFriend',
                                })
                            }}
                            myGroupChat={()=>{
                                this.props.navigation.navigate('myGroupChatScene' )
                            }}
                        />
                    </View>
                )
            }
        }
        
    }

    //这边返回的是A,0这样的数据
    _onSectionselect = (section, index) => {
        //跳转到某一项
        // this.refs.list.scrollToLocation({ animated: true, index: this.state.sectionSize[index] })
        console.log(index)
        console.log(section)
        this.refs.list.scrollToLocation({
            animated: true,
            sectionIndex: index,
            itemIndex: 0,
            viewPosition: 0,
            viewOffset: 0
        })
    }

    _getItemLayout(data, index) {
        // console.log(index,11);
        let [length, separator, header] = [ITEM_HEIGHT, SEPARATOR_HEIGHT, HEADER_HEIGHT];
        return { length, offset: (length + separator) * index + header, index };
    }
    //分组列表内容
    _renderItem = (item) => {
        return (
            <View style={styles.itemView}>
                <TouchableOpacity style={styles.itemPar}
                onPress={()=>{
                    console.log(123,item.item.uid)
                    this.props.navigation.navigate('friendInfo',{
                        friendId: item.item.uid,
                        nickname: item.item.nickname,
                        remark: item.item.remark  == '' ? item.item.nickname : item.item.remark,
                        headsmall: item.item.headsmall,
                    })
                }}>
                    <Image style={styles.imgLogo} source={{uri:item.item.headsmall}} />
                    <View style={styles.itemAlign}>
                        <Text style={{ fontSize: 15, color: '#333' }}>
                            {
                                item.item.remark == '' ? item.item.nickname : item.item.remark
                            }
                        </Text>
                    </View>
                    
                </TouchableOpacity>
            </View>
        )
    }
    //分组头
    _renderSectionHeader = (section) => {
        return (
            <View style={styles.headerView}>
                <Text style={styles.headerText}>{section.section.key}</Text>
            </View>
        )
    }
}
const styles = StyleSheet.create({
    viewPager: {
        flex: 1
    },
    pageStyle: {
        alignItems: 'center',
        padding: 20,
    },
    headerView: {
        justifyContent: 'center',
        height: HEADER_HEIGHT,
        paddingLeft: 20,
        backgroundColor: 'rgb(245,245,245)'
    },
    imgLogo: {
        // marginLeft: 8,
        // marginRight: 5,
        height: 40,
        // borderWidth: 1,
        // borderBottomLeftRadius: px2dp(70),
        // borderTopLeftRadius: px2dp(70),
        // borderBottomRightRadius: px2dp(70),
        // borderTopRightRadius: px2dp(70),
        width: px2dp(65),
    },
    headerText: {
        fontSize: 15,
        fontWeight: 'bold',
        color: '#3cb775'
    },
    itemView: {
        backgroundColor: '#fff',
        flexDirection: 'row',
        padding: 20,
        alignItems: 'center',
        height: ITEM_HEIGHT
    },
    itemPar:{
        flexDirection: 'row',
        
    },
    itemAlign:{
        marginLeft: 5,
        flex: 1,
        borderBottomWidth: .5,
        borderColor: 'rgb(245,245,245)',
        // alignItems: 'center',
        justifyContent: 'center',
    },
    parent:{
        flex:1,
        backgroundColor: 'rgb(245,245,245)',
        justifyContent:'center',
    },
    content:{
        alignSelf:'center',        
        justifyContent: 'center',
        // flexDirection: 'row',
        borderWidth:1,
        borderColor:'rgb(245,245,245)',
        borderRadius: 10,
        width:180,
        height:130,
    },
    noticeText:{
        marginTop:10,
        alignSelf: 'center',
        // fontSize:
    },
});















// export default class FriendScene extends Component {
    
//     render() {
//         return (
//             <View style={styles.viewPager} >
//                 <View style={styles.pageStyle}>
//                     <Text>联系人</Text>
//                 </View>

//             </View>
//         )

//     }

// }

// const styles = {
//     viewPager: {
//         flex: 1
//     },
//     pageStyle: {
//         alignItems: 'center',
//         padding: 20,
//     },
// }
